import { Component, OnInit } from '@angular/core';
import {MsgConstants} from '../../../../constants/constants';
import {SiteV2API} from '../../site-v2-constants';
import {ActivatedRoute, Router} from '@angular/router';
import {ResponseUtil} from '../../../../util/response-util';
import {MsgResult} from '../../../../models/msg-result';
import {TableUtil} from '../../../../util/table-util';
import {Path} from '../../../../portal/admin/admin-breadcrumb/breadcrumb';
import {OneDialogService} from '../../../../widgets/one-dialog/one-dialog.service';
import {PageSubject} from '../../../../util/page-subject';
import {SiteDevicesService} from '../site-devices.service';
import {SiteDevices} from '../site-devices';
import {DataDictionaryService} from '../../../../services/dataDictionary.service';

@Component({
  selector: 'app-device-assign-site',
  templateUrl: './device-assign-site.component.html',
  styleUrls: ['./device-assign-site.component.css']
})
export class DeviceAssignSiteComponent implements OnInit {

  table;

  siteName = '';
  siteCode = '';
  regionName = '';
  isAllocat = '1';
  siteCate = '';
  snCode = '';

  siteDevive: SiteDevices;

  allSiteCateArr: Array<any> = [];
  // 数据字典中获取数据的编码
  dicPolluteType = 'ZDLEWRY';
  dicPolluteArr: Array<any> = [];


  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private dicService: DataDictionaryService,
    private siteDeviceService: SiteDevicesService
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.loadSiteMonitor();
    this.getSiteDeviceById();
    this.getDicPolluteType()
  }
  /**
   * 实例化对象
   */
  private initObject() {
    this.siteDevive = new SiteDevices();
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path('设备接入管理', '');
    this.pageSubject.pushPage('设备管理', '分配站点', path);
  }

  /**
   * 搜索刷新
   */
  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 站点未绑定设备查询
   */
  loadSiteMonitor() {
    this.table = this.tableUtil.load('one_table_assign-site', {
      columns: [
        { checkbox: true },
        { field: 'id', title: 'ID', align: 'left', visible: false, switchable: false},
        { field: 'siteCode', title: '站点编码', align: 'left', visible: false, switchable: false},
        { field: 'siteName', title: '站点名称', align: 'left'},
        { field: 'snCode', title: '设备编号', align: 'left'},
        { field: 'siteTypeName', title: '站点类型', align: 'left'},
        { field: 'regionName', title: '行政区划' , align: 'left'},
        { field: 'address', title: '站点位置' , align: 'left'},
        { field: 'isThied', title: '第三方' , align: 'left', formatter : this.yesOrNoFormat},
        { field: 'isMove', title: '移动设备' , align: 'left', formatter : this.yesOrNoFormat},
        { field: 'isUse', title: '启用' , align: 'left', formatter : this.yesOrNoFormat},
        { field: 'createDate', title: '创建时间' , align: 'left' , sortName: 'CREATEDATE', sortable: true, visible: false}
      ],
      idField: 'id',
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      paginationLoop: false, // 是否开启循环分页
      singleSelect: true, // 单选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_mobile-assign-site',
      url: SiteV2API.sitePageListV2,
      method: 'post',
      // 传递附加参数
      queryParams: (params) => {
        params.siteTypeCode = this.siteCate;
        params.regionName = this.regionName;
        // params.isMove = '0';
        params.snCode = this.snCode;
        params.siteName = this.siteName;
        // params.isAllocat = this.isAllocat;
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        return this.responseUtil.bsPageHandler(result, () => {
          result.data.rows.forEach(function (value) {
            value.createDate = value.createDate || '';
            value.updateDate = value.updateDate || '';
          });
        });
      },
      height: 700, // table高度
      sortable: true,
      order: 'asc',
      sortName: 'UPDATEDATE',
      classes: 'table table-hover',
      striped: true, // 隔行变色
      mobileResponsive: true // 响应式
    });
  }
  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat = (value, row, index) => {
    if (value === '0') {
      return '否';
    }
    if (value === '1') {
      return '是';
    }
  };

  /**
   * 取消分配
   */
  cancelAssignSite() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }
  /**
   * 清空分配
   */
  clearAssignSite() {
    this.table.bootstrapTable('uncheckAll');
    this.siteDevive.siteCode = '';
    this.siteDevive.siteName = '';
    this.updateMobileDevSite();
  }
  /**
   * 保存分配
   */
  saveAssignSite() {
    const rows = this.table.bootstrapTable('getSelections');
    if (rows.length !== 1) {
      this.dialogService.modalInfo('请选择一条数据');
    } else {
      this.siteDevive.siteCode = this.tableUtil.getCloumn(rows[0], 'siteCode');
      this.siteDevive.siteName = rows[0].siteName;
      this.updateMobileDevSite();
    }
  }
  updateMobileDevSite = () => {
    this.siteDeviceService.siteMonitorEdit(this.siteDevive).subscribe(
      result => this.responseUtil.success(result, this.processResult),
      message => this.responseUtil.error(message)
    );
  };
  /**
   *  获取修改信息
   * @param result
   */
  private processResult = (result: MsgResult) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (this.siteDevive.siteCode) {
        this.dialogService.success('分配站点成功');
      } else {
        this.dialogService.success('清除站点成功');
      }
      this.cancelAssignSite();
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 通过Id获取移动设备
   */
  getSiteDeviceById() {
    const id = this.route.snapshot.params['id'];
    this.siteDeviceService.getSiteMonitorById(id).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data) {
            this.siteDevive = JSON.parse(JSON.stringify(result.data));
            this.siteDevive.updateDate = null;
            this.siteDevive.createDate = null;
            this.siteDevive.receiveTimeMonitor = null;
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * 获取所有站点类型
   */
  getAllSiteCate () {
    this.siteDeviceService.getAllSiteCate().subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            result.data.forEach( (val) => {
              this.dicPolluteArr.every((dic) => {
                if (val.monitorCategory === dic.value) {
                  val.cateName = dic.display;
                  return false;
                } else {
                  return true;
                }
              })
            });
            this.allSiteCateArr = [].concat(result.data);
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
  /**
   * 获取数据字典中站点类型-大类
   */
  getDicPolluteType () {
    this.dicService.getChildDicByCode(this.dicPolluteType).subscribe(
      result => this.responseUtil.success(result,  () => {
        if (result && result.code === MsgConstants.MSG_CODE_OK) {
          if (result.data.length > 0) {
            this.dicPolluteArr = result.data;
            this.getAllSiteCate();
          }
        }
        if (result && result.code !== MsgConstants.MSG_CODE_OK) {
          this.dialogService.info(result.message);
        }
      }),
      error => this.responseUtil.error(error)
    );
  }
}
